Skip to content

Latest commit

 

History

History
66 lines (54 loc) · 1.33 KB

面试题_阿里_查询数据.md

File metadata and controls

66 lines (54 loc) · 1.33 KB

提供了一个数组结构的 data,要求实现一个 query 方法,返回一个新的数组,query 方法内部有 过滤、排序、分组 等操作,并且支持链式调用,调用最终的 execute 方法返回结果:

const result = query(list)
  .where(item => item.age > 18)
  .sortBy('id')
  .groupBy('name')
  .execute();

console.log(result);

const list = [ { name: 'John', id: 1, age: 25 }, { name: 'Alice', id: 2, age: 30 }, { name: 'Bob', id: 3, age: 28 }, { name: 'Emily', id: 4, age: 22 }, { name: 'Michael', id: 5, age: 32 }, { name: 'Sara', id: 6, age: 27 }, { name: 'David', id: 7, age: 35 }, { name: 'Olivia', id: 8, age: 29 }, { name: 'Daniel', id: 9, age: 31 }, { name: 'Sophia', id: 10, age: 26 } ];

function query(list){
  let data = [...list];

  function where(callback){
    const temp = data.filter(callback)
    return query(temp)
  }

  function sortBy(key){
    const temp = data.sort((a,b)=>a[key]-b[key])
    return query(temp)
  }

  function groupBy(key){
    let temp = {}
    data.forEach(item => {
      const value = item[key];

      if (!temp[value]) {
        temp[value] = [];
      }

      temp[value].push(item);
    });
    return query([temp])
  }

  function execute(){
    return data;
  }

  return {
    where,
    sortBy,
    groupBy,
    execute
  }
}